package oop.ex3.serverprotocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import oop.ex3.nameserver.NameServer;
import oop.ex3.sharedclasses.IPaddress;

/**
 * Handles CONTAINFILE Message.
 * handles a client's request to update the NameServer of having a new file.
 * 
 * @author zablo
 *
 */
public class ContainFile extends ClientMessageHandler {

	@Override
	public boolean run(NameServer server,  IPaddress sessionIP,
			DataInputStream clientInput, DataOutputStream clientOutput) {
		try {
			String fileName = clientInput.readUTF();
			if (endsWithEnd(clientInput)==FAILURE){
				return FAILURE;
			}
			if (ServerMessageSender.done(clientOutput)==FAILURE){
				return FAILURE;
			}
			//TODO ASK @ FORUM:
			/*
			 * Im adding the file AFTER sending the DONE.
			 * There is a chance that because of sync, the file will be added later,
			 * while the FileManager 'thinks' the operation was complete.
			 * If we send DONE after adding the file,
			 * it may fail, and I'll have to remove the file -
			 * and then another problem - because of sync, other fileManagers may
			 * see the file in the NameServer, although it shouldn't be here.
			 * Can I add the file after sending DONE?
			 */
			server.addFile(sessionIP, fileName);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return FAILURE;
		}
		return SUCCESS;
	}

}
